package com.example.field.util;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class emailQQ {

    //发送用户的QQ账号
    private static final String emailUsername = "1103067119@qq.com";
    //发送用户的QQ邮箱密码（到平台获取）
    private static final String emailPassword = "szbwpbosoqqybabj";
    private static final String smtpHost = "smtp.qq.com";
    private static final int smtpPort = 465;

    /**
     * 发送邮件
     * @param recipientEmail 收件人邮箱地址
     * @param subject 邮件标题
     * @param content 邮件正文
     * @throws MessagingException 如果发送邮件时发生错误
     */
    public static void sendEmail(String recipientEmail, String subject, String content) throws MessagingException {

        if(!testRecipientEmail(recipientEmail)){
            return;
        }

        System.out.println("QQ邮件发送： "+"发送人："+emailUsername+" 发送密码："+emailPassword+" Host:"+smtpHost+" Port:"+smtpPort);
        System.out.println(" 收件人："+recipientEmail+" 标题："+subject+" 内容："+content);

        // 配置SMTP服务器信息
        Properties properties = new Properties();
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", String.valueOf(smtpPort));
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");

        // 创建会话
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailUsername, emailPassword);
            }
        });

        // 创建邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailUsername)); // 设置发件人
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail)); // 设置收件人
        message.setSubject(subject); // 设置主题
        message.setText(content); // 设置正文

        // 发送邮件
        Transport.send(message);
    }

    //测试邮件链接是否可用
    public static boolean testRecipientEmail(String recipientEmail) {
        try {
            new InternetAddress(recipientEmail, true);
            return true; // 地址有效
        } catch (AddressException e) {
            return false; // 地址无效
        }
    }

}
